import cgi
import datetime
import urllib
import os


from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext.db import djangoforms

# user profile Model.  I know we have a copy of this separately in data module
# but want to do a simpler version for now and one that includes
# the link to Google user account.
# we don't need email because we get that from Google Account
class Profile(db.Model):
    user = db.UserProperty(auto_current_user_add=True)
    firstname = db.StringProperty()
    lastname = db.StringProperty()
    city = db.StringProperty()
    state = db.StringProperty(default='MA')
    country = db.StringProperty(default='USA')

# this method handles looking up  a profile in the datastore
# if nothing found we create a new instance of the Profile Class
# this code is based on an example in Programming Google App Engine
# it seems to make some assumptions about attributes of the built
# in user object (viz. user_id)
def get_profile(user_id=None):
    if not user_id:
        user = users.get_current_user()
        if not user:
            return None
        user_id = user.user_id()
    key = db.Key.from_path('Profile', user_id)
    profile = db.get(key)
    if not profile:
        profile = Profile(key_name=user_id)
    return profile

# this is a form object that corresponds to the User model
class ProfileForm(djangoforms.ModelForm):
    class Meta:
        model = Profile
        exclude = ['user']

# render a page using the given template and return as a string
# we need the handler so we know what path to use in various links
# we add some standard user info to the passed in parameters
def render_page(handler, tname = 'index.html', values = { }):
    templ = os.path.join(
          os.path.dirname(__file__),
          'templates/' + tname)
    if not os.path.isfile(templ):
        return 'Error:  Template ' + tname + 'not found.'
    user = users.get_current_user()
    if not user:
        user_link = '<a href=' + users.create_login_url(handler.request.path) + '>Login or register</a>'
        is_logged_in = False
    else:
        # logout should redirect to home page
        user_link = 'Welcome, ' + user.nickname() + '!  <a href=' + users.create_logout_url("/") + '>Logout</a>'
        is_logged_in = True
    page_parameters = dict(values)
    page_parameters["user_link"] = user_link
    page_parameters["is_logged_in"] = is_logged_in
    return template.render(templ, page_parameters)

class MainPage(webapp.RequestHandler):
    def get(self):
        web_page = render_page(self,'index.html',{})
        self.response.out.write(web_page)

class ProfilePage(webapp.RequestHandler):
    def get(self):
        profile = get_profile()
        web_page = render_page(self,'profile.html',{"form":ProfileForm(instance=profile)})
        self.response.out.write(web_page)

    def post(self):
        profile = get_profile() # need to find current version so we can update it (not sure if needed)
        data = ProfileForm(data=self.request.POST, instance=profile)
        if data.is_valid():
            # save and redirect to home for now (consider whether maybe should show profile again instead)
            entity = data.save(commit=False)
            entity.put()
            self.redirect('/')
        else:
            # reshow the screen with error messages
            web_page = render_page(self,'profile.html',{"form":data})
            self.response.out.write(web_page)
            

class Login(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__),'login.html')
        self.response.out.write(template.render(path, {},True))
        
class Register(webapp.RequestHandler):
    def get(self):
        path = os.path.join(os.path.dirname(__file__),'register.html')
        self.response.out.write(template.render(path, {},True))


application = webapp.WSGIApplication(
                                     [('/', MainPage),('/profile', ProfilePage),('/login',Login),('/register',Register)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()




